//
//  RecentListView.swift
//  maozzi-rss
//
//  Created by 帽子 on 2020/6/14.
//  Copyright © 2020 帽子. All rights reserved.
//    最近阅读 view

import SwiftUI

struct RecentListView: View {
    @EnvironmentObject private var userData: UserData
    @State private var isPresented = false
    @State private var isAlert = false

    var body: some View {
        List {
            ForEach(self.userData.recentData.reversed(), id: \.self) { newsItem in
                Button(action: {
                    self.isPresented.toggle()
                }) {
                    NewsRowView(newsItem: newsItem).environmentObject(self.userData)
                }.sheet(isPresented: self.$isPresented) {
                    NewsDetailView(newsItem: newsItem).environmentObject(self.userData)
                }
            }
            .onDelete(perform: removeRows)
        }.navigationBarTitle(Text("最近阅读"), displayMode: .inline)
            .navigationBarItems(trailing: Button(action: {
                self.isAlert.toggle()
            }) {
                Text("全部删除")
            }.alert(isPresented: self.$isAlert) {
                // 删除确认
                Alert(title: Text("确认删除？"), primaryButton: .destructive(Text("朕已阅！"), action: {
                    self.userData.recentData = []
                    DispatchQueue.main.async(execute: {
                        _ = LocalCacheUtil.save(filename: UserData.recentCacheFileName, value: self.userData.recentData)
                    })
                }), secondaryButton: .cancel(Text("取消")))
            })
    }

    func removeRows(at offsets: IndexSet) {
        let index = userData.recentData.count - 1 - offsets.first!
        userData.recentData.remove(at: index)
        _ = LocalCacheUtil.save(filename: UserData.recentCacheFileName, value: self.userData.recentData)
    }
}

struct RecentListView_Previews: PreviewProvider {
    static var previews: some View {
        RecentListView().environmentObject(UserData())
    }
}
